package com.imay.base;

import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.os.Process;

import com.imay.base.helper.ActivityHelper;

import java.util.List;

/**
 * Created by jeaman on 2017/3/24.
 */

public abstract class BaseApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        initAllProcess();
        //只有主进程才初始化
        if (isMainProcess()) {
            //Activity生命周期监听
            registerActivityLifecycleCallbacks(ActivityHelper.getInstance());

            init();
        }

    }

    protected abstract void init();
    /*Umeng 推送需要在全部进程初始化*/
    protected abstract void initAllProcess();


    //多进程时,判断是否主进程
    private boolean isMainProcess() {
        ActivityManager am = ((ActivityManager) getSystemService(Context.ACTIVITY_SERVICE));
        List<ActivityManager.RunningAppProcessInfo> processInfos = am.getRunningAppProcesses();
        String mainProcessName = getPackageName();
        int myPid = Process.myPid();
        for (ActivityManager.RunningAppProcessInfo info : processInfos) {
            if (info.pid == myPid && mainProcessName.equals(info.processName)) {
                return true;
            }
        }
        return false;
    }

    public void exit() {
        try {
            ActivityHelper.getInstance().finishAllActivity();
            System.exit(0);
        } catch (Exception e) {
        }
    }

}
